<template>
  <el-config-provider :locale="zhCn">
    <div class="admin-container">
      <el-container>
        <el-header>
          <div class="header-title">社团管理系统 - 管理员端</div>
          <div class="header-user">
            <el-dropdown @command="handleCommand">
              <span class="user-info" @click="showUserInfo">
                <el-avatar :size="32" :src="userInfo.avatarUrl"></el-avatar>
                <span class="username">{{ userInfo.real_name }}</span>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                  <el-dropdown-item command="userInfo">个人信息</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
  
        <el-container>
          <el-aside width="200px">
            <el-menu
              :default-active="activeMenu"
              class="el-menu-vertical"
              @select="handleSelect"
            >
              <el-menu-item index="users">
                <el-icon><User /></el-icon>
                <span>用户管理</span>
              </el-menu-item>
              <el-menu-item index="clubs">
                <el-icon><House /></el-icon>
                <span>社团管理</span>
              </el-menu-item>
              <el-menu-item index="announcements">
                <el-icon><Bell /></el-icon>
                <span>系统公告</span>
              </el-menu-item>
              <el-menu-item index="activity">
                <el-icon><DataLine /></el-icon>
                <span>社团活跃度</span>
              </el-menu-item>
            </el-menu>
          </el-aside>
  
          <el-main>
            <!-- 用户管理部分 -->
            <div v-if="activeMenu === 'users'">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span>用户管理</span>
                    <el-form :inline="true" :model="userSearchForm">
                      <el-form-item>
                        <el-input
                          v-model="userSearchForm.realName"
                          placeholder="真实姓名"
                          clearable
                          @clear="loadUserList"
                        ></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-input
                          v-model="userSearchForm.idCard"
                          placeholder="身份证号"
                          clearable
                          @clear="loadUserList"
                        ></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="loadUserList">查询</el-button>
                        <el-button @click="resetUserSearch">重置</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </template>
  
                <el-table
                  :data="userList"
                  style="width: 100%"
                  v-loading="userLoading"
                  border
                  stripe
                  highlight-current-row
                >
                  <el-table-column
                    type="index"
                    label="用户ID"
                    width="80"
                    :index="userIndexMethod"
                  />
                  <el-table-column prop="username" label="用户名" width="120" />
                  <el-table-column prop="realName" label="真实姓名" width="120" />
                  <el-table-column prop="phone" label="手机号" width="120" />
                  <el-table-column prop="idCard" label="身份证号" width="180" />
                  <el-table-column prop="identity" label="身份" width="120">
                    <template #default="scope">
                      {{ scope.row.identity || '普通用户' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="clubNames" label="所属社团" width="150" />
                  <el-table-column label="头像" width="100">
                    <template #default="scope">
                      <el-image
                        :src="scope.row.avatarUrl"
                        fit="cover"
                        style="width: 40px; height: 40px; border-radius: 50%"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '启用' : '禁用' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                      <div class="user-actions-cell">
                        <el-button
                          size="small"
                          :type="scope.row.status === 1 ? 'danger' : 'success'"
                          @click="handleUserStatus(scope.row)"
                        >
                          {{ scope.row.status === 1 ? '禁用' : '启用' }}
                        </el-button>
                        <el-button
                          size="small"
                          type="danger"
                          @click="handleDeleteUser(scope.row)"
                        >删除</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
  
                <div class="pagination">
                  <el-pagination
                    :current-page="userCurrentPage"
                    :page-size="userPageSize"
                    :page-sizes="[10, 20, 30, 50]"
                    :total="userTotal"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleUserSizeChange"
                    @current-change="handleUserCurrentChange"
                  />
                </div>
              </el-card>
            </div>
  
            <!-- 社团管理部分 -->
            <div v-if="activeMenu === 'clubs'">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span>社团管理</span>
                    <el-form :inline="true" :model="clubSearchForm">
                      <el-form-item>
                        <el-input
                          v-model="clubSearchForm.name"
                          placeholder="社团名称"
                          clearable
                          @clear="searchClubs"
                        ></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-select v-model="clubSearchForm.status" placeholder="活动状态" clearable @clear="searchClubs">
                          <el-option label="全部" value="" />
                          <el-option label="正常" value="正常" />
                          <el-option label="暂停活动" value="暂停活动" />
                          <el-option label="已解散" value="已解散" />
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="searchClubs">查询</el-button>
                        <el-button @click="resetClubSearch">重置</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </template>
  
                <el-table
                  :data="clubList"
                  style="width: 100%"
                  v-loading="clubLoading"
                  border
                  stripe
                  highlight-current-row
                >
                  <el-table-column
                    type="index"
                    label="社团ID"
                    width="80"
                    :index="clubIndexMethod"
                  />
                  <el-table-column prop="name" label="社团名称" width="150" />
                  <el-table-column prop="description" label="描述" width="180" show-overflow-tooltip />
                  <el-table-column label="社团图片" width="100">
                    <template #default="scope">
                      <el-image
                        :src="scope.row.coverUrl"
                        fit="cover"
                        style="width: 40px; height: 40px; border-radius: 4px"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="审核状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getAuditStatusType(scope.row.status)">
                        {{ getAuditStatusText(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createdAt" label="创建时间" width="180">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.createdAt) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="adminName" label="管理员姓名" width="120" />
                  <el-table-column prop="adminAccount" label="管理员账户" width="180" />
                  <el-table-column prop="clubActivitiesStatus" label="活动状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getStatusType(scope.row.clubActivitiesStatus)">
                        {{ scope.row.clubActivitiesStatus }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="220" fixed="right">
                    <template #default="scope">
                      <div class="club-actions-cell">
                        <el-dropdown 
                          @command="(command) => handleClubStatus(scope.row, command)" 
                          style="margin-right: 10px"
                          :disabled="scope.row.status === 0 || scope.row.status === 2"
                        >
                          <el-button 
                            size="small" 
                            type="primary"
                            :disabled="scope.row.status === 0 || scope.row.status === 2"
                          >
                            活动<el-icon class="el-icon--right"><arrow-down /></el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item command="正常">正常</el-dropdown-item>
                              <el-dropdown-item command="暂停活动">暂停活动</el-dropdown-item>
                              <el-dropdown-item command="已解散">已解散</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                        <el-dropdown @command="(command) => handleClubAuditStatus(scope.row, command)">
                          <el-button size="small" type="warning">
                            审核<el-icon class="el-icon--right"><arrow-down /></el-icon>
                          </el-button>
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item command="0">待审核</el-dropdown-item>
                              <el-dropdown-item command="1">已通过</el-dropdown-item>
                              <el-dropdown-item command="2">已拒绝</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
  
                <div class="pagination">
                  <el-pagination
                    :current-page="clubCurrentPage"
                    :page-size="clubPageSize"
                    :page-sizes="[10, 20, 30, 50]"
                    :total="clubTotal"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleClubSizeChange"
                    @current-change="handleClubCurrentChange"
                  />
                </div>
                
              </el-card>
            </div>
            <!-- 系统公告部分 -->
            <div v-if="activeMenu === 'announcements'">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span>系统公告管理</span>
                    <el-form :inline="true" :model="announcementSearchForm">
                      <el-form-item>
                        <el-input
                          v-model="announcementSearchForm.keyWords"
                          placeholder="标题/内容"
                          clearable
                          @clear="searchAnnouncements"
                        ></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-select v-model="announcementSearchForm.status" placeholder="状态" clearable @clear="searchAnnouncements">
                          <el-option label="全部" value="" />
                          <el-option label="已发布" :value="1" />
                          <el-option label="草稿" :value="0" />
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-select v-model="announcementSearchForm.level" placeholder="级别" clearable @clear="searchAnnouncements">
                          <el-option label="全部" value="" />
                          <el-option label="系统级" value="系统级" />
                          <el-option label="社团级" value="社团级" />
                        </el-select>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="searchAnnouncements">查询</el-button>
                        <el-button @click="resetAnnouncementSearch">重置</el-button>
                      </el-form-item>
                    </el-form>
                    <el-button type="primary" @click="handleOpenCreateDraftDialog">
                      创建草稿
                    </el-button>
                    <el-button type="primary" @click="handleOpenPublishDialog('publish-new')">
                      发布新公告
                    </el-button>
                  </div>
                </template>

                <el-table
                  :data="announcementList"
                  style="width: 100%"
                  v-loading="announcementLoading"
                  border
                  stripe
                >
                  <el-table-column type="index" label="序号" width="80" />
                  <el-table-column prop="title" label="公告标题" width="200" />
                  <el-table-column prop="content" label="公告内容" show-overflow-tooltip />
                  <el-table-column prop="type" label="公告类型" width="100">
                    <template #default="scope">
                      <el-tag>{{ scope.row.type }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
                        {{ scope.row.status === 1 ? '已发布' : '草稿' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="level" label="公告级别" width="100">
                    <template #default="scope">
                      <el-tag :type="scope.row.level === '系统级' ? 'danger' : 'warning'">{{ scope.row.level }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="createdByName" label="发布人" width="120" />
                  <el-table-column prop="createdAt" label="发布时间" width="180">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.createdAt) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="updatedAt" label="更新时间" width="180">
                    <template #default="scope">
                      {{ formatDateTime(scope.row.updatedAt) }}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                      <div class="announcement-actions-cell">
                        <el-button
                          size="small"
                          type="primary"
                          @click="handleOpenPublishDialog('publish-draft', scope.row)"
                          :disabled="scope.row.status === 1"
                        >发布</el-button>
                        <el-button
                          size="small"
                          type="danger"
                          @click="handleDeleteAnnouncement(scope.row)"
                        >删除</el-button>
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pagination">
                  <el-pagination
                    :current-page="announcementCurrentPage"
                    :page-size="announcementPageSize"
                    :page-sizes="[10, 20, 30, 50]"
                    :total="announcementTotal"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleAnnouncementSizeChange"
                    @current-change="handleAnnouncementCurrentChange"
                  />
                </div>
              </el-card>

              <!-- 创建公告草稿对话框 -->
              <el-dialog
                v-model="createDraftDialogVisible"
                title="创建公告草稿"
                width="50%"
              >
                <el-form :model="createDraftForm" label-width="100px">
                  <el-form-item label="公告标题" required>
                    <el-input v-model="createDraftForm.title" />
                  </el-form-item>
                  <el-form-item label="公告内容" required>
                    <el-input
                      v-model="createDraftForm.content"
                      type="textarea"
                      :rows="4"
                    />
                  </el-form-item>
                  <el-form-item label="公告类型" required>
                    <el-select v-model="createDraftForm.type" placeholder="请选择公告类型">
                      <el-option label="通知" value="NOTICE" />
                      <el-option label="活动" value="EVENT" />
                      <el-option label="系统" value="SYSTEM" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="公告级别">
                    <span class="form-item-static-text">系统级</span>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="createDraftDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveDraft">保存草稿</el-button>
                  </span>
                </template>
              </el-dialog>

              <!-- 新增/编辑/发布公告对话框 -->
              <el-dialog
                v-model="announcementDialogVisible"
                :title="dialogTitle"
                width="50%"
              >
                <el-form :model="announcementForm" label-width="100px">
                  <el-form-item label="公告标题" required>
                    <el-input v-model="announcementForm.title" />
                  </el-form-item>
                  <el-form-item label="公告内容" required>
                    <el-input
                      v-model="announcementForm.content"
                      type="textarea"
                      :rows="4"
                    />
                  </el-form-item>
                  <el-form-item label="公告类型" required>
                    <el-select v-model="announcementForm.type" placeholder="请选择公告类型">
                      <el-option label="通知" value="NOTICE" />
                      <el-option label="活动" value="EVENT" />
                      <el-option label="系统" value="SYSTEM" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="公告级别">
                    <span class="form-item-static-text">系统级</span>
                  </el-form-item>
                  <el-form-item label="发送方式" required>
                    <el-radio-group v-model="announcementForm.sendType" @change="handleSendTypeChange">
                      <el-radio label="broadcast">广播给所有用户</el-radio>
                      <el-radio label="multiple">发送给指定用户</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  
                  <!-- 当选择发送给指定用户时显示用户选择 -->
                  <el-form-item v-if="announcementForm.sendType === 'multiple'" label="选择用户">
                    <el-select
                      v-model="announcementForm.receiverIds"
                      multiple
                      filterable
                      remote
                      :remote-method="searchUsers"
                      placeholder="请输入用户名/真实姓名搜索"
                      style="width: 100%"
                      v-loading="userSearchLoading"
                    >
                      <el-option
                        v-for="user in userSearchList"
                        :key="user.id"
                        :label="user.username + (user.realName ? '（' + user.realName + '）' : '') + ' | ' + (user.role || '普通用户')"
                        :value="user.id"
                      >
                        <div style="display: flex; align-items: center; justify-content: flex-start; padding: 0 6px; min-width: 180px;">
                          <span style="font-size: 15px; color: #333; flex: 1; text-align: left;">
                            {{ user.username }}<span v-if="user.realName">（{{ user.realName }}）</span>
                          </span>
                          <el-tag size="small" :type="getRoleTagType(user.role)" style="margin-left: 8px; min-width: 60px; text-align: center;">
                            {{ user.role || '普通用户' }}
                          </el-tag>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="announcementDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveAnnouncement">保存</el-button>
                  </span>
                </template>
              </el-dialog>
            </div>
            <!-- 社团活跃度部分 -->
            <div v-if="activeMenu === 'activity'">
              <el-card class="box-card">
                <template #header>
                  <div class="card-header">
                    <span>社团活跃度分析</span>
                    <el-form :inline="true" :model="activitySearchForm">
                      <el-form-item>
                        <el-date-picker
                          v-model="activitySearchForm.dateRange"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :shortcuts="dateShortcuts"
                          @change="handleDateRangeChange"
                        />
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="loadActivityData">查询</el-button>
                        <el-button @click="resetActivitySearch">重置</el-button>
                      </el-form-item>
                    </el-form>
                  </div>
                </template>

                <div class="activity-content">
                  <!-- 活跃度统计卡片 -->
                  <div class="activity-cards">
                    <el-card class="activity-card">
                      <template #header>
                        <div class="activity-card-header">
                          <span>总活跃度</span>
                        </div>
                      </template>
                      <div class="activity-card-content">
                        <span class="activity-value">{{ totalActivity }}</span>
                        <span class="activity-unit">分</span>
                      </div>
                    </el-card>
                    <el-card class="activity-card">
                      <template #header>
                        <div class="activity-card-header">
                          <span>平均活跃度</span>
                        </div>
                      </template>
                      <div class="activity-card-content">
                        <span class="activity-value">{{ averageActivity }}</span>
                        <span class="activity-unit">分</span>
                      </div>
                    </el-card>
                    <el-card class="activity-card">
                      <template #header>
                        <div class="activity-card-header">
                          <span>最高活跃度</span>
                        </div>
                      </template>
                      <div class="activity-card-content">
                        <span class="activity-value">{{ maxActivity }}</span>
                        <span class="activity-unit">分</span>
                      </div>
                    </el-card>
                  </div>

                  <!-- 活跃度趋势图 -->
                  <div class="activity-chart">
                    <el-card>
                      <template #header>
                        <div class="chart-header">
                          <span>社团活动活跃度日趋势</span>
                        </div>
                      </template>
                      <!-- 添加图表描述 -->
                      <p class="chart-description">此图表展示了选定日期范围内，每日社团活动数量的变化趋势。</p>
                      <div ref="activityChartRef" style="width: 100%; height: 400px;"></div>
                    </el-card>
                  </div>

                  <!-- 社团活跃度排行 -->
                  <div class="activity-ranking">
                    <el-card>
                      <template #header>
                        <div class="ranking-header">
                          <span>社团活跃度排行</span>
                        </div>
                      </template>
                      <el-table
                        :data="clubActivityList"
                        style="width: 100%"
                        v-loading="activityLoading"
                        border
                        stripe
                        fit
                      >
                        <el-table-column type="index" label="排名" width="80" />
                        <el-table-column prop="clubName" label="社团名称" width="180" />
                        <el-table-column prop="activityScore" label="活跃度" width="120">
                          <template #default="scope">
                            <el-tag :type="getActivityTagType(scope.row.activityScore)">
                              {{ scope.row.activityScore }}分
                            </el-tag>
                          </template>
                        </el-table-column>
                        <el-table-column prop="memberCount" label="成员数" width="120" />
                        <el-table-column prop="eventCount" label="活动数" width="120" />
                        <el-table-column prop="lastActivityTime" label="最近活动时间" width="180">
                          <template #default="scope">
                            {{ formatDateTime(scope.row.lastActivityTime) }}
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-card>
                  </div>
                </div>
              </el-card>
            </div>
          </el-main>
        </el-container>
      </el-container>
    </div>

    <!-- 个人信息编辑对话框 -->
    <el-dialog v-model="personalInfoDialogVisible" title="编辑个人信息" width="50%">
      <el-form :model="personalInfoForm" label-width="100px" ref="personalInfoFormRef">
        <el-form-item label="用户名">
          <el-input v-model="personalInfoForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="personalInfoForm.realName"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="personalInfoForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="personalInfoForm.email"></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="personalInfoForm.idCard"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatarFile">
          <div style="display: flex; flex-direction: column; align-items: flex-start;">
            <el-avatar :size="80" :src="personalInfoAvatarPreviewUrl" style="margin-bottom: 10px;"></el-avatar>
            <el-upload class="upload-demo" action="#" :auto-upload="false" :on-change="handlePersonalInfoAvatarUpload" :limit="1" accept="image/*" :show-file-list="false">
              <template #trigger>
                <el-button type="primary">选择新头像</el-button>
              </template>
            </el-upload>
            <div class="el-upload__tip">请上传图片文件，且不超过 5MB</div>
          </div>
        </el-form-item>
        <!-- 以下字段仅用于展示，不提供编辑 -->
        <el-form-item label="用户ID">
          <span class="form-item-static-text">{{ personalInfoForm.userId }}</span>
        </el-form-item>
        <el-form-item label="创建时间">
          <span class="form-item-static-text">{{ formatDateTime(personalInfoForm.createdAt) }}</span>
        </el-form-item>
        <el-form-item label="最后登录">
          <span class="form-item-static-text">{{ formatDateTime(personalInfoForm.lastLogin) }}</span>
        </el-form-item>
        <el-form-item label="角色">
          <span class="form-item-static-text">{{ personalInfoForm.role || '普通用户' }}</span>
        </el-form-item>
        <el-form-item label="状态">
          <span class="form-item-static-text">{{ personalInfoForm.status === 1 ? '启用' : '禁用' }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="personalInfoDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPersonalInfoForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </el-config-provider>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, House, ArrowDown, Bell, DataLine } from '@element-plus/icons-vue'
import axios from 'axios'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import { Client } from '@stomp/stompjs'
import SockJS from 'sockjs-client'
import * as echarts from 'echarts'

// 配置axios基础URL
axios.defaults.baseURL = 'http://localhost:8080/LZ'
axios.defaults.withCredentials = true

const router = useRouter()
const activeMenu = ref('users')
const userInfo = ref({
  username: '',
  avatarUrl: '',
  real_name: ''
})

// WebSocket相关状态
const stompClient = ref(null);
const connected = ref(false);

// 系统公告相关
const announcementList = ref([])
const announcementTotal = ref(0)
const announcementCurrentPage = ref(1)
const announcementPageSize = ref(10)
const announcementLoading = ref(false)
const announcementDialogVisible = ref(false)
const dialogTitle = ref('发布新公告')
const announcementForm = ref({
  id: '',
  title: '',
  content: '',
  type: 'NOTICE',
  status: 0, // 0: 草稿, 1: 已发布
  level: '系统级', // 级别固定为系统级
  createdAt: '',
  sendType: 'broadcast', // 默认广播: broadcast, multiple: 发送给指定用户
  receiverIds: [],
  mode: 'publish-new' // 用于区分是发布新公告还是发布草稿
})
const announcementSearchForm = ref({
  keyWords: '',
  status: '',
  level: ''
})

// 用户管理相关
const userList = ref([])
const userTotal = ref(0)
const userCurrentPage = ref(1)
const userPageSize = ref(10)
const userLoading = ref(false)
const userSearchForm = ref({
  realName: '',
  idCard: ''
})

// 社团管理相关
const clubList = ref([])
const clubTotal = ref(0)
const clubCurrentPage = ref(1)
const clubPageSize = ref(10)
const clubLoading = ref(false)
const clubSearchForm = ref({
  name: '',
  status: ''
})

// 用户搜索相关
const userSearchList = ref([])
const userSearchLoading = ref(false)

// 新增用户信息对话框状态
const userInfoDialogVisible = ref(false)

// 社团活跃度相关
const activitySearchForm = ref({
  dateRange: []
})
const activityLoading = ref(false)
const totalActivity = ref(0)
const averageActivity = ref(0)
const maxActivity = ref(0)
const clubActivityList = ref([])
const activityChartRef = ref(null)
let activityChart = null

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 显示用户信息对话框
const showUserInfo = () => {
  // 从本地存储获取完整的用户信息
  const storedUserInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  if (storedUserInfo) {
    // 填充个人信息编辑表单
    personalInfoForm.value = {
      userId: storedUserInfo.id,
      username: storedUserInfo.username,
      realName: storedUserInfo.real_name || '',
      phone: storedUserInfo.phone || '',
      email: storedUserInfo.email || '',
      idCard: storedUserInfo.id_card || '',
      avatarFile: null, // 编辑时默认为空
      createdAt: storedUserInfo.createdAt || '',
      lastLogin: storedUserInfo.lastLogin || '',
      role: storedUserInfo.role || '',
      status: storedUserInfo.status
    };
    // 保存原始信息用于比较
    originalPersonalInfo.value = {
      realName: storedUserInfo.real_name || '',
      phone: storedUserInfo.phone || '',
      email: storedUserInfo.email || '',
      idCard: storedUserInfo.id_card || '',
      avatarUrl: storedUserInfo.avatarUrl || ''
    };
    // 设置头像预览
    personalInfoAvatarPreviewUrl.value = storedUserInfo.avatarUrl || '';
    // 打开编辑对话框
    personalInfoDialogVisible.value = true;
  } else {
    ElMessage.error('无法获取个人信息，请重新登录。');
    router.push('/login');
  }
}

// 初始化加载
onMounted(async () => {
  try {
    // 从本地存储读取完整的 userInfo JSON 字符串
    const storedUserInfoString = localStorage.getItem('userInfo');
    console.log('从本地存储读取 userInfo 原始字符串:', storedUserInfoString);

    if (storedUserInfoString) {
      try {
        // 解析 JSON 字符串
        const storedUserInfo = JSON.parse(storedUserInfoString);
        console.log('解析后的 storedUserInfo 对象:', storedUserInfo);

        // 更新 userInfo 响应式对象的值
        userInfo.value.username = storedUserInfo.username || '';
        userInfo.value.avatarUrl = storedUserInfo.avatarUrl || '';
        userInfo.value.real_name = storedUserInfo.real_name || '';

        console.log('mounted 阶段更新后的 userInfo:', userInfo.value);

      } catch (parseError) {
        console.error('解析本地存储的 userInfo 失败:', parseError);
        // 可选：提示用户重新登录或清除本地存储
        // ElMessage.error('用户信息解析失败，请尝试重新登录');
      }
    } else {
        console.log('本地存储中未找到 userInfo');
    }

    checkAdminRole();
    connectWebSocket(); // 连接WebSocket

    if (activeMenu.value === 'users') {
      await loadUserList()
    } else if (activeMenu.value === 'announcements') {
      await loadAnnouncementList()
    }
  } catch (error) {
    ElMessage.error('初始化失败：' + (error.message || '未知错误'))
  }
})

onUnmounted(() => {
  disconnectWebSocket(); // 断开WebSocket连接
})

// WebSocket连接方法
const connectWebSocket = () => {
  const userId = localStorage.getItem('userId');
  if (!userId) {
    console.error('无法获取用户ID');
    ElMessage.error('WebSocket连接失败：无法获取用户ID');
    return;
  }
  const socket = new SockJS('http://localhost:8080/LZ/ws');
  stompClient.value = new Client({
    webSocketFactory: () => socket,
    debug: (str) => {
      console.log('STOMP: ' + str);
    },
    reconnectDelay: 5000,
    heartbeatIncoming: 4000,
    heartbeatOutgoing: 4000,
    connectHeaders: {
      'user': userId
    }
  });

  stompClient.value.onConnect = () => {
    console.log('已连接到WebSocket服务器, 用户ID:', userId);
    connected.value = true;

    // 订阅广播消息
    stompClient.value.subscribe('/topic/broadcast', onMessageReceived);

    // 订阅私聊消息
    stompClient.value.subscribe('/user/queue/private', onMessageReceived);
  };

  stompClient.value.onStompError = (frame) => {
    console.error('STOMP错误:', frame);
    connected.value = false;
    ElMessage.error('WebSocket连接错误：' + (frame.headers?.message || '未知错误'));
  };

  stompClient.value.onWebSocketError = (event) => {
    console.error('WebSocket错误:', event);
    connected.value = false;
    ElMessage.error('WebSocket连接错误，请检查网络连接');
  };

  stompClient.value.onWebSocketClose = (event) => {
    console.log('WebSocket连接关闭:', event);
    connected.value = false;
  };

  stompClient.value.activate();
};

const disconnectWebSocket = () => {
  if (stompClient.value) {
    stompClient.value.deactivate();
    connected.value = false;
    console.log('WebSocket连接已断开');
  }
};

const onMessageReceived = (payload) => {
  try {
    const message = JSON.parse(payload.body);
    console.log('收到WebSocket消息:', message);
    // 获取当前用户ID
    const currentUserId = localStorage.getItem('userId');
//将message.senderId转为字符串
const currentUserIdStr = String(message.senderId);
    if (currentUserIdStr === currentUserId) {
      console.log('忽略自己发送的消息');
      return; // 忽略自己发送的消息
    }
    // 根据消息类型显示不同的提示
    if (message.code === 200) {
      ElMessage.success(message.message || '消息发送成功');
    } else {
      ElMessage.warning(message.message || '收到新消息');
    }
  } catch (e) {
    console.error('处理接收到的消息失败:', e);
    ElMessage.error('消息处理失败：' + e.message);
  }
};

// 检查管理员角色
const checkAdminRole = () => {
  const role = localStorage.getItem('role')
  if (role !== '系统管理员') {
    ElMessage.error('无权访问管理员页面')
    router.push('/login')
  }
}

// 用户管理方法
const loadUserList = async () => {
  userLoading.value = true
  try {
    const response = await axios.post('/admin/getUserPage', {
      pageNum: userCurrentPage.value,
      pageSize: userPageSize.value,
      realName: userSearchForm.value.realName,
      idCard: userSearchForm.value.idCard
    })
    if (response.data.code === 200) {
      userList.value = response.data.data.data || []
      userTotal.value = typeof response.data.data.total === 'number' ? response.data.data.total : 0
    } else {
      throw new Error(response.data.message || '获取用户列表失败')
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data.message || '获取用户列表失败')
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
  } finally {
    userLoading.value = false
  }
}

const resetUserSearch = () => {
  userSearchForm.value = {
    realName: '',
    idCard: ''
  }
  userCurrentPage.value = 1
  loadUserList()
}

const handleUserStatus = async (user) => {
  try {
    const newStatus = user.status === 1 ? '0' : '1'
    await axios.post('/admin/setUserstatus', null, {
      params: {
        userId: user.userId,
        status: newStatus
      }
    })
    ElMessage.success('状态修改成功')
    loadUserList()
  } catch (error) {
    ElMessage.error('修改用户状态失败')
  }
}

const handleDeleteUser = async (user) => {
  try {
    // 先检查用户是否为社团管理员
    const adminResponse = await axios.post('/admin/getUserClubAdmin', null, {
      params: {
        userId: user.userId
      }
    })
    
    let confirmMessage = '确定要删除该用户吗？'
    if (adminResponse.data.code === 200) {
      // 用户是社团管理员
      confirmMessage = `该用户是${adminResponse.data.data}的管理员，确定要删除吗？`
    }
    
    await ElMessageBox.confirm(confirmMessage, '提示', {
      type: 'warning'
    })
    
    await axios.post('/admin/deleteUser', null, {
      params: {
        userId: user.userId,
        username: user.username
      }
    })
    ElMessage.success('删除成功')
    loadUserList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败')
    }
  }
}

// 社团管理方法
const loadClubList = async () => {
  clubLoading.value = true
  try {
    const response = await axios.post('/admin/getClubPage', {
      pageNum: clubCurrentPage.value,
      pageSize: clubPageSize.value,
      name: clubSearchForm.value.name,
      status: clubSearchForm.value.status
    })
    if (response.data.code === 200) {
      clubList.value = response.data.data.data || []
      clubTotal.value = typeof response.data.data.total === 'number' ? response.data.data.total : 0
    }
  } catch (error) {
    ElMessage.error('获取社团列表失败')
  } finally {
    clubLoading.value = false
  }
}

const resetClubSearch = () => {
  clubSearchForm.value = {
    name: '',
    status: ''
  }
  clubCurrentPage.value = 1
  loadClubList()
}

const handleClubStatus = async (club, status) => {
  try {
    // 检查审核状态
    if (club.status === 0 || club.status === 2) {
      ElMessage.warning('只有审核通过的社团才能修改活动状态');
      return;
    }
    
    console.log('修改活动状态参数:', club, status);
    await axios.post('/admin/setClubactivity_status', null, {
      params: {
        clubId: club.id,
        activity_status: status
      }
    });
    ElMessage.success('活动状态修改成功');
    loadClubList();
  } catch (error) {
    ElMessage.error('修改活动状态失败');
    console.error('Error updating club status:', error);
  }
};

const handleClubAuditStatus = async (club, status) => {
  try {
    console.log('修改审核状态参数:', club, status);
    await axios.post('/admin/setClubstatus', null, {
      params: {
        clubId: club.id,
        status: status
      }
    })
    ElMessage.success('审核状态修改成功')
    loadClubList()
  } catch (error) {
    ElMessage.error('修改审核状态失败')
    console.error('Error updating club audit status:', error);
  }
}

const getStatusType = (status) => {
  switch (status) {
    case '正常':
      return 'success'
    case '暂停活动':
      return 'warning'
    case '已解散':
      return 'danger'
    default:
      return 'info'
  }
}

// 分页方法
const handleUserSizeChange = (val) => {
  userPageSize.value = val
  loadUserList()
}

const handleUserCurrentChange = (val) => {
  userCurrentPage.value = val
  loadUserList()
}

const handleClubSizeChange = (val) => {
  clubPageSize.value = val
  loadClubList()
}

const handleClubCurrentChange = (val) => {
  clubCurrentPage.value = val
  loadClubList()
}

// 修改搜索用户方法
const searchUsers = async (query) => {
  userSearchLoading.value = true
  try {
    // 总是发送请求，即使query为空字符串
    const response = await axios.get('/admin/searchUsers', {
      params: {
        keyword: query
      }
    })
    if (response.data.code === 200) {
      // 只显示状态为启用且身份不是系统管理员的用户
      userSearchList.value = response.data.data.filter(user => user.status === 1 && user.role !== '系统管理员')
    } else {
       userSearchList.value = [] // 请求失败时清空列表
    }
  } catch (error) {
    console.error('搜索用户失败:', error)
    ElMessage.error('搜索用户失败')
    userSearchList.value = [] // 发生错误时清空列表
  } finally {
    userSearchLoading.value = false
  }
}

const searchClubs = () => {
  clubCurrentPage.value = 1
  loadClubList()
}

// 菜单选择
const handleSelect = (key) => {
  activeMenu.value = key
  if (key === 'clubs') {
    loadClubList()
  } else if (key === 'users') {
    loadUserList()
  } else if (key === 'announcements') {
    loadAnnouncementList()
  }
}

// 用户操作
const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await axios.post('/club/logout');
      localStorage.removeItem('token');
      localStorage.removeItem('role');
      localStorage.removeItem('userInfo');
      localStorage.removeItem("clubInfo");
      localStorage.removeItem('userId');
      router.push('/login');
      ElMessage.success('已成功退出登录');
    } catch (error) {
      console.error('登出失败:', error);
      ElMessage.error('登出操作失败，请稍后重试');
      localStorage.removeItem('token');
      localStorage.removeItem('role');
      localStorage.removeItem('userInfo');
      localStorage.removeItem("clubInfo");
      router.push('/login');
    }
  } else if (command === 'userInfo') {
    showUserInfo();
  }
}

const userIndexMethod = (index) => {
  return (userCurrentPage.value - 1) * userPageSize.value + index + 1
}

const clubIndexMethod = (index) => {
  return (clubCurrentPage.value - 1) * clubPageSize.value + index + 1
}

const getAuditStatusText = (status) => {
  switch (Number(status)) {
    case 0:
      return '审核中'
    case 1:
      return '已通过'
    case 2:
      return '已拒绝'
    default:
      return '未知'
  }
}

const getAuditStatusType = (status) => {
  switch (Number(status)) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return 'info'
  }
}

const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 加载公告列表
const loadAnnouncementList = async () => {
  announcementLoading.value = true
  try {
    const response = await axios.post('/admin/announcements', {
      pageNum: announcementCurrentPage.value,
      pageSize: announcementPageSize.value,
      keyWords: announcementSearchForm.value.keyWords,
      status: announcementSearchForm.value.status,
      level: announcementSearchForm.value.level
    })
    if (response.data.code === 200) {
      announcementList.value = response.data.data.list || []
      announcementTotal.value = response.data.data.total || 0
    } else {
      throw new Error(response.data.message || '获取公告列表失败')
    }
  } catch (error) {
    ElMessage.error('获取公告列表失败：' + (error.message || '未知错误'))
  } finally {
    announcementLoading.value = false
  }
}


// 搜索公告
const searchAnnouncements = () => {
  announcementCurrentPage.value = 1
  loadAnnouncementList()
}

// 重置搜索
const resetAnnouncementSearch = () => {
  announcementSearchForm.value = {
    keyWords: '',
    status: '',
    level: ''
  }
  announcementCurrentPage.value = 1
  loadAnnouncementList()
}

// 处理每页显示数量变化
const handleAnnouncementSizeChange = (val) => {
  announcementPageSize.value = val
  loadAnnouncementList()
}

// 处理当前页变化
const handleAnnouncementCurrentChange = (val) => {
  announcementCurrentPage.value = val
  loadAnnouncementList()
}

// 新增创建草稿相关状态
const createDraftDialogVisible = ref(false)
const createDraftForm = ref({
  title: '',
  content: '',
  type: 'NOTICE',
  level: '系统级' // 创建草稿时固定为系统级
})

// 新增函数：打开创建公告草稿对话框
const handleOpenCreateDraftDialog = () => {
  createDraftForm.value = {
    title: '',
    content: '',
    type: 'NOTICE',
    level: '系统级'
  }
  createDraftDialogVisible.value = true
}

// 新增函数：保存草稿
const saveDraft = async () => {
  try {
    // 表单验证
    if (!createDraftForm.value.title) {
      ElMessage.error('公告标题不能为空')
      return
    }
    if (!createDraftForm.value.content) {
      ElMessage.error('公告内容不能为空')
      return
    }
    if (!createDraftForm.value.type) {
      ElMessage.error('请选择公告类型')
      return
    }
     if (createDraftForm.value.level !== '系统级') {
       // 以防万一还是验证一下内部值
       ElMessage.error('公告级别必须为系统级')
       return
    }

    // 构建请求体
    const payload = {
      title: createDraftForm.value.title,
      content: createDraftForm.value.content,
      type: createDraftForm.value.type,
      level: '系统级', // 级别固定为系统级
      status: 0, // 创建草稿状态设为0
      senderId: localStorage.getItem('userId') // 添加创建者ID
    }

    const response = await axios.post('/admin/createAnnouncement', payload);

    if (response.data.code === 200) {
      ElMessage.success('草稿创建成功')
      createDraftDialogVisible.value = false
      // 刷新公告列表
      searchAnnouncements()
    } else {
      ElMessage.error(response.data.message || '创建失败')
    }
  } catch (error) {
    console.error('创建草稿失败:', error)
    ElMessage.error('操作失败：' + (error.response?.data?.message || error.message))
  }
}

// 重命名并修改函数：打开发布公告对话框（包括发布新公告和发布草稿）
const handleOpenPublishDialog = (mode, data = null) => {
  // 初始化announcementForm，用于发布流程
  announcementForm.value = {
    id: data?.id || null, // 发布新公告时为null
    title: data?.title || '',
    content: data?.content || '',
    type: data?.type || 'NOTICE',
    status: 1, // 发布新公告或发布草稿都默认设置为已发布状态
    level: data?.level || '系统级', // 固定为系统级
    createdAt: data?.createdAt || '',
    sendType: 'broadcast', // 发布新公告或草稿时，默认发送方式为广播
    receiverIds: [],
    mode: mode // 保存当前模式
  }

  if (mode === 'publish-new') {
    dialogTitle.value = '发布新公告'
    // 发布新公告强制状态为1，发送方式默认广播，接收者列表为空

  } else if (mode === 'publish-draft') {
    dialogTitle.value = '发布公告'
    // 从草稿数据继承字段，但发送方式默认广播，接收者列表清空，status设为1
    announcementForm.value.sendType = 'broadcast';
    announcementForm.value.receiverIds = [];
  }

  // 确保级别为系统级
  announcementForm.value.level = '系统级';

  announcementDialogVisible.value = true
}

const getRoleTagType = (role) => {
  switch (role) {
    case '系统管理员':
      return 'danger'
    case '社团管理员':
      return 'warning'
    case '普通用户':
      return 'info'
    default:
      return 'info'
  }
}

// 新增函数：保存公告（草稿或发布）
const saveAnnouncement = async () => {
  try {
    // 表单验证 (确保标题、内容、类型非空)
    if (!announcementForm.value.title) {
      ElMessage.error('公告标题不能为空')
      return
    }
    if (!announcementForm.value.content) {
      ElMessage.error('公告内容不能为空')
      return
    }
    if (!announcementForm.value.type) {
      ElMessage.error('请选择公告类型')
      return
    }
    if (announcementForm.value.sendType === 'multiple' && (!announcementForm.value.receiverIds || announcementForm.value.receiverIds.length === 0)) {
         ElMessage.error('请选择接收用户');
         return;
    }

    const userId = localStorage.getItem('userId');
    if (!userId) {
        ElMessage.error('无法获取当前用户ID，请重新登录');
        router.push('/login');
        return;
    }

    // 构建请求体
    const payload = {
      id: announcementForm.value.id, // 始终使用原始ID，无论是新公告还是草稿
      title: announcementForm.value.title,
      content: announcementForm.value.content,
      type: announcementForm.value.type,
      level: '系统级', // 级别固定为系统级
      status: 1, // 发布状态
      senderId: parseInt(userId), // 发送者为当前管理员ID
      receiverIds: announcementForm.value.sendType === 'multiple' ? announcementForm.value.receiverIds : []
    }

    // 根据模式决定调用创建还是更新接口
    const url = announcementForm.value.mode === 'publish-draft' ? '/admin/updateAnnouncement' : '/admin/createAnnouncement'
    const response = await axios.post(url, payload);

    if (response.data.code === 200 && response.data.data) {
      announcementDialogVisible.value = false;
      searchAnnouncements();

      // 如果成功发布或更新，通过WebSocket发送消息
      if (connected.value) {
        try {
          const websocketMessage = {
            id: payload.id || response.data.data, // 如果是更新，使用原有id；如果是新建，使用返回的id
            title: announcementForm.value.title,
            content: announcementForm.value.content,
            type: announcementForm.value.type,
            level: announcementForm.value.level,
            senderId: parseInt(userId),
            receiverIds: announcementForm.value.receiverIds,
            sendTime: new Date().toISOString()
          };

          console.log('通过WebSocket发送公告消息:', websocketMessage);

          // 根据发送类型选择不同的发送方式
          if (announcementForm.value.sendType === 'broadcast') {
            stompClient.value.publish({
              destination: '/app/send',
              body: JSON.stringify(websocketMessage)
            });
          } else {
            // 群发消息
            stompClient.value.publish({
              destination: '/app/send',
              body: JSON.stringify(websocketMessage)
            });
          }

          ElMessage.success(announcementForm.value.mode === 'publish-draft' ? '公告更新成功' : '公告发布成功');
        } catch (error) {
          console.error('WebSocket发送失败:', error);
          ElMessage.error(error.message || '发送公告失败');
        }
      } else {
        ElMessage.warning('WebSocket未连接，公告已保存但可能未发送成功');
      }
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    console.error('保存/发布公告失败:', error);
    ElMessage.error('操作失败：' + (error.response?.data?.message || error.message));
  }
}

// 新增：个人信息编辑相关状态和方法
const personalInfoDialogVisible = ref(false);
const personalInfoFormRef = ref(null);
const personalInfoForm = ref({
  userId: null,
  username: '',
  realName: '',
  phone: '',
  email: '',
  idCard: '',
  avatarFile: null, // 用于存储新的头像文件
  createdAt: '',
  lastLogin: '',
  role: '',
  status: null
});
const personalInfoAvatarPreviewUrl = ref('');
const originalPersonalInfo = ref({
    realName: '',
    phone: '',
    email: '',
    idCard: '',
    avatarUrl: ''
});

// 新增：处理个人信息头像上传
const handlePersonalInfoAvatarUpload = (file) => {
  if (file) {
    const isImage = file.raw.type.startsWith('image/');
    const isLt5M = file.raw.size / 1024 / 1024 < 5;
    if (!isImage) {
      ElMessage.error('只能上传图片文件！');
      personalInfoForm.value.avatarFile = null;
      personalInfoAvatarPreviewUrl.value = originalPersonalInfo.value.avatarUrl;
      return false;
    }
    if (!isLt5M) {
      ElMessage.error('图片大小不能超过 5MB！');
      personalInfoForm.value.avatarFile = null;
      personalInfoAvatarPreviewUrl.value = originalPersonalInfo.value.avatarUrl;
      return false;
    }
    personalInfoForm.value.avatarFile = file.raw;
    personalInfoAvatarPreviewUrl.value = URL.createObjectURL(file.raw);
    return true;
  }
  personalInfoForm.value.avatarFile = null;
  personalInfoAvatarPreviewUrl.value = originalPersonalInfo.value.avatarUrl;
  return false;
};

// 新增：提交个人信息表单
const submitPersonalInfoForm = async () => {
  try {
    // 可以在这里添加表单验证逻辑，使用 personalInfoFormRef
    // 例如：personalInfoFormRef.value.validate(async (valid) => { if (!valid) return; ... });

    const formData = new FormData();

    // 构建更新请求对象，只包含被修改的字段
    const updatePayload = {
      userId: personalInfoForm.value.userId,
      // 检查字段是否修改，只发送修改过的字段
      realName: personalInfoForm.value.realName !== originalPersonalInfo.value.realName ? personalInfoForm.value.realName : null,
      phone: personalInfoForm.value.phone !== originalPersonalInfo.value.phone ? personalInfoForm.value.phone : null,
      email: personalInfoForm.value.email !== originalPersonalInfo.value.email ? personalInfoForm.value.email : null,
      idCard: personalInfoForm.value.idCard !== originalPersonalInfo.value.idCard ? personalInfoForm.value.idCard : null,
      originalAvatarUrl: originalPersonalInfo.value.avatarUrl // 发送原始头像URL以便后端判断是否需要删除旧头像
    };

    // 添加文件（如果有新头像文件）
    if (personalInfoForm.value.avatarFile) {
      formData.append('file', personalInfoForm.value.avatarFile);
    } else {
       // 如果没有新头像文件，但原始头像URL存在，发送一个空文件表示不更新头像
       // 如果原始头像URL也不存在，则不发送文件字段
       if(originalPersonalInfo.value.avatarUrl) {
          const emptyBlob = new Blob([''], { type: 'application/octet-stream' });
          formData.append('file', emptyBlob, ''); // 空文件名表示不上传新文件
       }
    }

    // 添加更新请求对象为 JSON 字符串
    formData.append('updatePersonalInfoRequestDto', new Blob([JSON.stringify(updatePayload)], { type: 'application/json' }));

    // 调用后端 API 进行更新
    // 请根据您的后端接口实际情况修改这里的 URL 和请求方法
    const response = await axios.post('/admin/updatePersonalInfo', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    });

    if (response.data.code === 200) {
      ElMessage.success('个人信息更新成功');
      personalInfoDialogVisible.value = false;

      // 更新本地存储的用户信息
      const updatedUserInfo = JSON.parse(localStorage.getItem('userInfo'));
      if (updatePayload.realName !== null) updatedUserInfo.real_name = updatePayload.realName;
      if (updatePayload.phone !== null) updatedUserInfo.phone = updatePayload.phone;
      if (updatePayload.email !== null) updatedUserInfo.email = updatePayload.email;
      if (updatePayload.idCard !== null) updatedUserInfo.id_card = updatePayload.idCard;
      // 如果后端返回了新的头像URL，更新本地存储和userInfo ref
      if (response.data.data && response.data.data.avatarUrl) {
        updatedUserInfo.avatarUrl = response.data.data.avatarUrl;
      }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo));

      // 更新页面上显示的用户信息（如果需要，例如顶部的头像和姓名）
      userInfo.value = updatedUserInfo; // 这会触发顶部 userInfo 的更新

    } else {
      ElMessage.error(response.data.message || '更新个人信息失败');
    }
  } catch (error) {
    console.error('更新个人信息失败:', error);
    ElMessage.error('更新个人信息网络错误');
  }
};

// 加载活跃度数据
const loadActivityData = async () => {
  activityLoading.value = true
  try {
    const [startDate, endDate] = activitySearchForm.value.dateRange || []
    const response = await axios.post('/admin/getClubActivity', {
      startDate: startDate ? startDate.toISOString() : null,
      endDate: endDate ? endDate.toISOString() : null
    })
    
    if (response.data.code === 200) {
      const data = response.data.data
      totalActivity.value = data.totalActivity || 0
      // 格式化平均活跃度为两位小数
      averageActivity.value = (data.averageActivity || 0).toFixed(2)
      maxActivity.value = data.maxActivity || 0
      clubActivityList.value = data.clubActivityList || []
      
      // 更新图表
      updateActivityChart(data.trendData || [])
    } else {
      throw new Error(response.data.message || '获取活跃度数据失败')
    }
  } catch (error) {
    ElMessage.error('获取活跃度数据失败：' + (error.message || '未知错误'))
  } finally {
    activityLoading.value = false
  }
}

// 更新活跃度趋势图
const updateActivityChart = (trendData) => {
  if (!activityChartRef.value || !activityChart) return
  
  const option = {
    // 添加图表主标题
    title: {
        text: '社团活动活跃度日趋势',
        left: 'center',
        textStyle: {
            color: '#22577a',
            fontSize: 18
        }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      // 定制 tooltip 格式
      formatter: function (params) {
          params = params[0];
          return '日期: ' + params.name + '<br/>活动数: ' + params.value;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: trendData.map(item => item.date),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '活动数' // 将名称改为"活动数"更精确
    },
    series: [
      {
        name: '活动数', // 将系列名称改为"活动数"
        type: 'line',
        smooth: true,
        data: trendData.map(item => item.value),
        areaStyle: {
          opacity: 0.3
        },
        itemStyle: {
          color: '#8fd6e1'
        },
        lineStyle: {
          color: '#38a3a5'
        }
      }
    ],
    // 添加图例
    legend: {
        data: ['活动数'],
        bottom: '0',
        left: 'center'
    }
  }
  
  activityChart.setOption(option)
}

// 重置活跃度搜索
const resetActivitySearch = () => {
  activitySearchForm.value.dateRange = []
  loadActivityData()
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  loadActivityData()
}

// 获取活跃度标签类型
const getActivityTagType = (score) => {
  if (score >= 80) return 'success'
  if (score >= 60) return 'warning'
  return 'danger'
}

// 监听窗口大小变化，调整图表大小
const handleResize = () => {
  if (activityChart) {
    activityChart.resize()
  }
}

// 监听菜单变化
watch(activeMenu, (newValue) => {
  if (newValue === 'activity') {
    nextTick(() => {
      if (activityChart) {
        activityChart.dispose()
      }
      activityChart = echarts.init(activityChartRef.value)
      loadActivityData()
    })
  } else if (activityChart) {
    activityChart.dispose()
    activityChart = null
  }
})

// 在组件挂载时添加事件监听
onMounted(() => {
  window.addEventListener('resize', handleResize)
})

// 在组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (activityChart) {
    activityChart.dispose()
    activityChart = null
  }
})

</script>

<style scoped>
.admin-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f7fafc 0%, #e3f6f5 100%);
}

.el-header {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 32px;
  box-shadow: 0 2px 12px rgba(100, 200, 180, 0.08);
  height: 64px;
  border-bottom: 1.5px solid #e3e8ee;
}

.header-title {
  font-size: 24px;
  font-weight: bold;
  color: #22577a;
  letter-spacing: 2px;
}

.header-user {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 4px 12px;
  border-radius: 20px;
  background: rgba(255,255,255,0.7);
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.08);
  transition: background 0.3s;
}

.user-info:hover {
  background: #e3f6f5;
}

.username {
  margin-left: 10px;
  color: #22577a;
  font-size: 15px;
  font-weight: 500;
}

.el-avatar {
  border: 2px solid #b8e1dd;
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.10);
}

.el-aside {
  background: #f7fafc;
  border-right: 1.5px solid #e3e8ee;
  box-shadow: 2px 0 8px rgba(100, 200, 180, 0.04);
}

.el-menu-vertical {
  border-right: none;
  padding: 24px 0;
  background: transparent;
}

.el-menu-item {
  height: 48px;
  line-height: 48px;
  margin: 8px 0;
  padding: 0 24px !important;
  border-radius: 12px;
  font-size: 16px;
  color: #22577a;
  transition: background 0.2s, color 0.2s;
}

.el-menu-item:hover {
  background: #e3f6f5 !important;
  color: #38a3a5 !important;
}

.el-menu-item.is-active {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%) !important;
  color: #22577a !important;
  font-weight: bold;
}

.el-main {
  padding: 32px;
  background: transparent;
  max-height: calc(100vh - 64px); /* 减去头部高度 */
  overflow-y: auto; /* Y轴滚动 */
}

.box-card {
  border-radius: 16px;
  box-shadow: 0 4px 24px 0 rgba(100, 200, 180, 0.10);
  background: #fff;
  border: 1.5px solid #e3e8ee;
  margin-bottom: 32px;
  transition: box-shadow 0.2s;
}

.box-card:hover {
  box-shadow: 0 8px 32px 0 rgba(100, 200, 180, 0.18);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 24px;
  border-bottom: 1px solid #ebeef5;
  background: #f7fafc;
  border-radius: 16px 16px 0 0;
}

.card-header span {
  font-size: 18px;
  font-weight: bold;
  color: #22577a;
}

.el-form--inline .el-form-item {
  margin-right: 18px;
  margin-bottom: 0;
}

.el-input, .el-select {
  border-radius: 8px;
  min-width: 140px;
}

.el-input__inner, .el-select .el-input__inner {
  border-radius: 8px !important;
}

.el-table {
  margin-top: 18px;
  border-radius: 12px;
  overflow: hidden;
  background: #fafdff;
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.06);
}

.el-table th {
  background: #e3f6f5 !important;
  font-weight: bold;
  color: #22577a;
  font-size: 15px;
}

.el-table td {
  padding: 10px 0; /* 减小垂直内边距 */
  font-size: 15px;
}

.el-tag {
  border-radius: 6px;
  padding: 0 10px;
  height: 26px;
  line-height: 26px;
  font-size: 14px;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.el-button {
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 500;
  font-size: 15px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(100, 200, 180, 0.12);
}

.el-button--primary {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%);
  border: none;
  color: #22577a;
}

.el-button--primary:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
}

.el-button--danger {
  background: linear-gradient(90deg, #ffb4a2 0%, #ffdac1 100%);
  border: none;
  color: #b0413e;
}

.el-button--danger:hover {
  background: linear-gradient(90deg, #ffdac1 0%, #ffb4a2 100%);
  color: #e76f51;
}

.el-button--warning {
  background: linear-gradient(90deg, #ffe066 0%, #ffd166 100%);
  border: none;
  color: #b08900;
}

.el-button--warning:hover {
  background: linear-gradient(90deg, #ffd166 0%, #ffe066 100%);
  color: #e9c46a;
}

.el-dropdown-menu {
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(100, 200, 180, 0.10);
  padding: 4px 0;
}

.el-dropdown-menu__item {
  padding: 10px 20px;
  font-size: 15px;
}

.el-dropdown-menu__item:hover {
  background: #e3f6f5;
}

::-webkit-scrollbar {
  width: 8px;
  background: #e3f6f5;
}
::-webkit-scrollbar-thumb {
  background: #b8e1dd;
  border-radius: 4px;
}

.form-item-static-text {
  font-size: 14px;
  color: #606266;
}

.el-dialog__header {
  padding: 16px 24px;
  margin-right: 0;
  border-bottom: 1px solid #f0f0f0;
}

.el-dialog__title {
  font-size: 17px;
  font-weight: 500;
}

.el-dialog__body {
  padding: 20px 24px;
}

.el-dialog__footer {
  padding: 12px 24px;
  border-top: 1px solid #f0f0f0;
}

/* 修改社团管理操作按钮样式，使其与提供的图片样式一致 */
.el-table__body-wrapper .el-button--primary, /* 修改活动状态按钮 (对应图片左侧发布按钮样式) */
.el-table__body-wrapper .el-button--warning /* 修改审核状态按钮 (对应图片右侧删除按钮样式) */
{
  border-radius: 20px; /* 增加圆角 */
  font-weight: bold;
  transition: all 0.2s;
  padding: 8px 20px; /* 调整内边距 */
  border: none; /* 移除边框 */
}

/* 为修改活动状态按钮添加图片左侧按钮的蓝绿色渐变 */
.el-table__body-wrapper .el-button--primary {
  background: linear-gradient(90deg, #8fd6e1 0%, #b8e1dd 100%); /* 蓝绿色渐变 */
  color: #22577a; /* 深蓝色文字 */
}

.el-table__body-wrapper .el-button--primary:hover {
  background: linear-gradient(90deg, #b8e1dd 0%, #8fd6e1 100%);
  color: #38a3a5;
}

/* 为修改审核状态按钮添加图片右侧按钮的粉橙色渐变 */
.el-table__body-wrapper .el-button--warning {
   background: linear-gradient(90deg, #ffb4a2 0%, #ffdac1 100%); /* 粉橙色渐变 */
   color: #b0413e; /* 深红色文字 */
}

.el-table__body-wrapper .el-button--warning:hover {
   background: linear-gradient(90deg, #ffdac1 0%, #ffb4a2 100%);
   color: #e76f51;
}

/* 调整社团管理操作列按钮的间距 */
.el-table__body-wrapper .el-button + .el-button {
    margin-left: 0; /* 将 margin-left 设为 0，使用父容器的 gap */
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

/* 新增社团管理操作按钮容器样式 */
.club-actions-cell {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 10px; /* 增加按钮之间的间隔 */
}

/* 新增用户管理操作按钮容器样式 */
.user-actions-cell {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 20px; /* 增加按钮之间的间隔 */
}

/* 新增公告管理操作按钮容器样式 */
.announcement-actions-cell {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 20px; /* 增加按钮之间的间隔 */
}

/* 社团活跃度相关样式 */
.activity-content {
  padding: 20px;
}

.activity-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.activity-card {
  transition: transform 0.3s;
}

.activity-card:hover {
  transform: translateY(-5px);
}

.activity-card-header {
  font-size: 16px;
  font-weight: bold;
  color: #22577a;
}

.activity-card-content {
  display: flex;
  align-items: baseline;
  justify-content: center;
  padding: 20px 0;
}

.activity-value {
  font-size: 36px;
  font-weight: bold;
  color: #38a3a5;
  margin-right: 8px;
}

.activity-unit {
  font-size: 16px;
  color: #606266;
}

.activity-chart {
  margin-bottom: 20px;
}

.chart-header {
  font-size: 16px;
  font-weight: bold;
  color: #22577a;
}

.ranking-header {
  font-size: 16px;
  font-weight: bold;
  color: #22577a;
}

.activity-ranking {
  margin-top: 20px;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .activity-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media screen and (max-width: 768px) {
  .activity-cards {
    grid-template-columns: 1fr;
  }
}

.activity-chart {
  margin-bottom: 20px;
}

.chart-header {
  font-size: 16px;
  font-weight: bold;
  color: #22577a;
}

/* 新增图表描述样式 */
.chart-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 15px; /* 留白 */
  text-align: center;
}

.ranking-header {
  font-size: 16px;
  font-weight: bold;
  color: #22577a;
}

/* 针对社团活跃度排行卡片主体移除内边距 */
.activity-ranking .el-card__body {
  padding: 0 !important; /* 移除内边距 */
}
</style>